package com.lqk.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Scanner;

public class ClientDemo {
    public static void main(String[] args) throws Exception {
        // 1 获取通道，绑定主机和端口号
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",8080));

        // 2 切换到非阻塞模式
        socketChannel.configureBlocking(false);

        // 3 创建Buffer
        ByteBuffer clientByteBuffer = ByteBuffer.allocate(1024);

        Scanner sc=new Scanner(System.in);
        while (sc.hasNext()){
            String message = sc.next();

            // 4 写入数据到 Buffer
            clientByteBuffer.put((new Date().toString()+"---->"+message).getBytes());

            // 5 模式切换
            clientByteBuffer.flip();

            // 6 写入通道
            socketChannel.write(clientByteBuffer);

            // 7 清空、关闭
            clientByteBuffer.clear();
        }

    }
}
